package xyz.schwi.cels.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import xyz.schwi.cels.dao.BaseDao;
import xyz.schwi.cels.entity.*;
import xyz.schwi.cels.service.BaseService;
import xyz.schwi.cels.util.BeanFactory;
import xyz.schwi.cels.util.InputUtil;
import xyz.schwi.cels.view.Menu;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author schwi
 * @date 2021/9/29 0029  14:46
 */
public class App {
    public static void main(String[] args) {
        BaseDao baseDao = (BaseDao) BeanFactory.getBean("baseDao");
        BaseService baseService = (BaseService) BeanFactory.getBean("baseService");
        Menu menu = new Menu();
        menu.title();
        boolean lastTime;
        boolean flag = true;
        while (flag) {
            menu.mainMenu();
            int choice = Integer.decode(InputUtil.getLine(null));
            switch (choice) {
                //浏览基库[单词和词汇]
                case 1:
                    boolean flag1 = true;
                    while (flag1) {
                        menu.firstMenu();
                        choice = Integer.decode(InputUtil.getLine(null));
                        switch (choice) {
                            //浏览单词
                            case 1:
                                menu.characterMenu();
                                Character c = InputUtil.getLine("请选择首字母").toUpperCase().charAt(0);
                                int pageNow = 1;
                                try {
                                    Map<Character, List<Word>> wordsMap = baseDao.getWordsMap("data\\w.dic");
                                    while (true) {
                                        if (!wordsMap.containsKey(c)) {
                                            break;
                                        }
                                        PageBean<Word> pageBean = baseService.selectWords("data\\w.dic", c, 15, pageNow++);
                                        pageBean.getData().forEach(System.out::println);
                                        if (!pageBean.isHasNext() || !"y".equalsIgnoreCase(InputUtil.getLine("下一页(第" + (pageBean.getPageNow() + 1) + "页,共" + (pageBean.getTotalPages() + 1) + "页)？[y/n]"))) {
                                            break;
                                        }
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                break;
                            //浏览词汇
                            case 2:
                                try {
                                    PageBean<Vocabulary> pageBean = baseService.selectVocabularies("data\\v.dic", 15, 1);
                                    int integer = Integer.decode(InputUtil.getLine("请选择页码(共" + (pageBean.getTotalPages() + 1) + "页)"));
                                    do {
                                        pageBean = baseService.selectVocabularies("data\\v.dic", 15, integer++);
                                        pageBean.getData().forEach(System.out::println);
                                    } while (pageBean.isHasNext() && "y".equalsIgnoreCase(InputUtil.getLine("下一页(第" + (pageBean.getPageNow() + 1) + "页,共" + (pageBean.getTotalPages() + 1) + "页)？[y/n]")));
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                break;
                            //返回上一级
                            default:
                                flag1 = false;
                                break;
                        }
                    }
                    break;
                //做游戏学习单词[随机性]
                case 2:
                    menu.secondMenu();
                    choice = Integer.decode(InputUtil.getLine(null));
                    lastTime = "y".equalsIgnoreCase(InputUtil.getLine("是否从上次继续？[y/n]"));
                    try {
                        File file;
                        NewTest newTest;
                        List<Base> words;
                        int count;
                        long startTime;
                        long endTime;
                        String json;
                        StringBuilder save = new StringBuilder();
                        switch (choice) {
                            case 1:
                                file = new File("data\\history\\en.dic");
                                if (lastTime && file.exists()) {
                                    newTest = baseService.continueGame("data\\history\\en.dic", "data\\history\\en.json");
                                } else {
                                    newTest = baseService.newGame();
                                }
                                //System.out.println(newTest);
                                words = newTest.getTestList();
                                count = newTest.getRight() + newTest.getError();
                                if (words == null) {
                                    System.err.println("没有单词");
                                    break;
                                }
                                if (count == words.size()) {
                                    newTest.setRight(0);
                                    newTest.setError(0);
                                    count = newTest.getRight() + newTest.getError();
                                }
                                startTime = System.currentTimeMillis();
                                for (int i = count; i < words.size(); i++) {
                                    String cn = InputUtil.getLine(words.get(i).getEn());
                                    if ("e".equals(cn) || "q".equals(cn)) {
                                        break;
                                    }
                                    boolean right = true;
                                    for (String s : words.get(i).getCn()) {
                                        if (s.equalsIgnoreCase(cn)) {
                                            System.out.println("回答正确");
                                            newTest.setRight(newTest.getRight() + 1);
                                            right = false;
                                            break;
                                        }
                                    }
                                    if (right) {
                                        System.err.println("回答错误");
                                        newTest.setError(newTest.getError() + 1);
                                    }
                                }
                                endTime = System.currentTimeMillis();
                                newTest.setSpendTime(newTest.getSpendTime() + endTime - startTime);
                                newTest.setFinishTime(endTime);
                                if (!file.exists()) {
                                    boolean mkdirs = file.getParentFile().mkdirs();
                                    boolean newFile = file.createNewFile();
                                }
                                for (int i = 0; i < newTest.getTestList().size(); i++) {
                                    if (i == newTest.getTestList().size() - 1) {
                                        save.append(newTest.getTestList().get(i).save());
                                        break;
                                    }
                                    save.append(newTest.getTestList().get(i).save()).append("\n");
                                }
                                json = JSON.toJSONString(newTest);
                                IoUtil.write(new FileOutputStream("data\\history\\en.json"), true, json.getBytes());
                                IoUtil.write(new FileOutputStream("data\\history\\en.dic"), true, save.toString().getBytes());
                                System.out.println("英译中回答结束, 答对" + newTest.getRight() + "题答错" + newTest.getError() + "题");
                                break;
                            case 2:
                                file = new File("data\\history\\cn.dic");
                                if (lastTime && file.exists()) {
                                    newTest = baseService.continueGame("data\\history\\cn.dic", "data\\history\\cn.json");
                                } else {
                                    newTest = baseService.newGame();
                                }
                                //System.out.println(newTest);
                                words = newTest.getTestList();
                                count = newTest.getRight() + newTest.getError();
                                if (words == null) {
                                    System.err.println("没有单词");
                                    break;
                                }
                                if (count == words.size()) {
                                    newTest.setRight(0);
                                    newTest.setError(0);
                                    count = newTest.getRight() + newTest.getError();
                                }
                                startTime = System.currentTimeMillis();
                                for (int i = count; i < words.size(); i++) {
                                    String en = InputUtil.getLine(words.get(i).getCn().get((int) (Math.random() * words.get(i).getCn().size())));
                                    ;
                                    if ("e".equals(en) || "q".equals(en)) {
                                        break;
                                    }
                                    boolean right = true;
                                    if (words.get(i).getEn().equalsIgnoreCase(en)) {
                                        System.out.println("回答正确");
                                        newTest.setRight(newTest.getRight() + 1);
                                        right = false;
                                        break;
                                    }
                                    if (right) {
                                        System.err.println("回答错误");
                                        newTest.setError(newTest.getError() + 1);
                                    }
                                }
                                endTime = System.currentTimeMillis();
                                newTest.setSpendTime(newTest.getSpendTime() + endTime - startTime);
                                newTest.setFinishTime(endTime);
                                if (!file.exists()) {
                                    boolean mkdirs = file.getParentFile().mkdirs();
                                    boolean newFile = file.createNewFile();
                                }
                                for (int i = 0; i < newTest.getTestList().size(); i++) {
                                    if (i == newTest.getTestList().size() - 1) {
                                        save.append(newTest.getTestList().get(i).save());
                                        break;
                                    }
                                    save.append(newTest.getTestList().get(i).save()).append("\n");
                                }
                                json = JSON.toJSONString(newTest);
                                IoUtil.write(new FileOutputStream("data\\history\\cn.json"), true, json.getBytes());
                                IoUtil.write(new FileOutputStream("data\\history\\cn.dic"), true, save.toString().getBytes());
                                System.out.println("中译英回答结束, 答对" + newTest.getRight() + "题答错" + newTest.getError() + "题");
                                break;
                            default:
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                //测试自己的水平[随机性]
                case 3:
                    menu.thirdMenu();
                    try {
                        File file;
                        NewTest newTest;
                        NewTest errTest;
                        NewTest errSave = new NewTest(0, 0, 0L, 0L, new ArrayList<>());
                        List<Base> words;
                        long startTime;
                        long endTime;
                        String json;
                        String cn;
                        String en;
                        StringBuilder save = new StringBuilder();
                        file = new File("data\\score\\test.dic");
                        if (file.exists()) {
                            errTest = baseService.readErrTest("data\\score\\test.dic", "data\\score\\test.json", false);
                        } else {
                            errTest = new NewTest(0, 0, 0L, 0L, new ArrayList<>());
                        }
                        int num = Integer.decode(InputUtil.getLine("多少题？"));
                        newTest = baseService.newTest("data\\w.dic", "data\\v.dic", num);
                        words = newTest.getTestList();
                        if (words == null) {
                            System.err.println("没有单词");
                            break;
                        }
                        startTime = System.currentTimeMillis();
                        for (int i = 0; i < words.size(); i++) {
                            boolean right = true;
                            if (Math.random() < 0.5) {
                                en = InputUtil.getLine(words.get(i).getCn().get((int) (Math.random() * words.get(i).getCn().size())));
                                if ("e".equals(en) || "q".equals(en)) {
                                    break;
                                }
                                if (words.get(i).getEn().equalsIgnoreCase(en)) {
                                    right = false;
                                }
                            } else {
                                cn = InputUtil.getLine(words.get(i).getEn());
                                if ("e".equals(cn) || "q".equals(cn)) {
                                    break;
                                }
                                for (String s : words.get(i).getCn()) {
                                    if (s.equalsIgnoreCase(cn)) {
                                        right = false;
                                        break;
                                    }
                                }
                            }
                            if (right) {
                                System.err.println("回答错误");
                                newTest.setError(newTest.getError() + 1);
                                if (words.get(i) instanceof Word) {
                                    errSave.getTestList().add(new ErrorWord(words.get(i), 3));
                                } else {
                                    errSave.getTestList().add(new ErrorVocabulary(words.get(i), 3));
                                }
                            } else {
                                System.out.println("回答正确");
                                newTest.setRight(newTest.getRight() + 1);
                            }
                        }
                        endTime = System.currentTimeMillis();
                        newTest.setSpendTime(newTest.getSpendTime() + endTime - startTime);
                        newTest.setFinishTime(endTime);
                        for (int i = 0; i < errSave.getTestList().size(); i++) {
                            save.append(errSave.getTestList().get(i).save()).append("\n");
                        }
                        boolean mkdirs = file.getParentFile().mkdirs();
                        boolean mkdirs1 = new File("data\\error\\error.json").getParentFile().mkdirs();
                        //
                        json = JSON.toJSONString(newTest);
                        IoUtil.write(new FileOutputStream("data\\score\\test.json"), true, json.getBytes());
                        //
                        json = JSON.toJSONString(errTest);
                        IoUtil.write(new FileOutputStream("data\\error\\error.json"), true, json.getBytes());
                        //
                        IoUtil.write(new FileOutputStream("data\\error\\error.dic", true), true, save.toString().getBytes());
                        System.out.println("英译中回答结束, 答对" + newTest.getRight() + "题答错" + newTest.getError() + "题");
                        break;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                //生词表
                case 4:
                    menu.forthMenu();
                    choice = Integer.decode(InputUtil.getLine(null));
                    switch (choice) {
                        case 1:
                            try {
                                PageBean<Base> pageBean = baseService.selectAll("data\\error\\error.dic", 15, 1);
                                int integer = Integer.decode(InputUtil.getLine("请选择页码(共" + (pageBean.getTotalPages() + 1) + "页)"));
                                do {
                                    pageBean = baseService.selectAll("data\\error\\error.dic", 15, integer++);
                                    pageBean.getData().forEach(System.out::println);
                                } while (pageBean.isHasNext() && "y".equalsIgnoreCase(InputUtil.getLine("下一页(第" + (pageBean.getPageNow() + 1) + "页,共" + (pageBean.getTotalPages() + 1) + "页)？[y/n]")));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            break;
                        case 2:
                            try {
                                File file;
                                NewTest errTest;
                                List<Base> words = null;
                                String json;
                                String cn;
                                String en;
                                StringBuilder save = new StringBuilder();
                                file = new File("data\\error\\error.dic");
                                if (file.exists()) {
                                    errTest = baseService.readErrTest("data\\error\\error.dic", "data\\error\\error.json", true);
                                    words = baseDao.selectError("data\\error\\error.dic");
                                } else {
                                    errTest = new NewTest(0, 0, 0L, 0L, new ArrayList<>());
                                }
                                if (words == null) {
                                    System.err.println("没有单词");
                                    break;
                                }
                                for (int i = words.size() - 1; i >= 0; i--) {
                                    boolean right = true;
                                    if (Math.random() < 0.5) {
                                        en = InputUtil.getLine(words.get(i).getCn().get((int) (Math.random() * words.get(i).getCn().size())));
                                        if ("e".equals(en) || "q".equals(en)) {
                                            break;
                                        }
                                        if (words.get(i).getEn().equalsIgnoreCase(en)) {
                                            right = false;
                                        }
                                    } else {
                                        cn = InputUtil.getLine(words.get(i).getEn());
                                        if ("e".equals(cn) || "q".equals(cn)) {
                                            break;
                                        }
                                        for (String s : words.get(i).getCn()) {
                                            if (s.equalsIgnoreCase(cn)) {
                                                right = false;
                                                break;
                                            }
                                        }
                                    }
                                    if (right) {
                                        System.err.println("回答错误");
                                        errTest.setError(errTest.getError() + 1);
                                    } else {
                                        System.out.println("回答正确");
                                        errTest.setRight(errTest.getRight() + 1);
                                        if (words.get(i) instanceof ErrorWord) {
                                            ((ErrorWord) words.get(i)).setErrorTime(((ErrorWord) words.get(i)).getErrorTime() - 1);
                                            if (((ErrorWord) words.get(i)).getErrorTime() <= 0) {
                                                words.remove(i);
                                            }
                                        } else {
                                            ((ErrorVocabulary) words.get(i)).setErrorTime(((ErrorVocabulary) words.get(i)).getErrorTime() - 1);
                                            if (((ErrorVocabulary) words.get(i)).getErrorTime() <= 0) {
                                                words.remove(i);
                                            }
                                        }
                                    }
                                }
                                errTest.setTestList(words);
                                for (int i = 0; i < errTest.getTestList().size(); i++) {
                                    save.append(errTest.getTestList().get(i).save()).append("\n");
                                }
                                boolean mkdirs = file.getParentFile().mkdirs();
                                boolean mkdirs1 = new File("data\\error\\error.json").getParentFile().mkdirs();
                                //
                                json = JSON.toJSONString(errTest);
                                IoUtil.write(new FileOutputStream("data\\error\\error.json"), true, json.getBytes());
                                //
                                IoUtil.write(new FileOutputStream("data\\error\\error.dic"), true, save.toString().getBytes());
                                System.out.println("生词本回答结束, 已累计答对" + errTest.getRight() + "题答错" + errTest.getError() + "题");
                                break;
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            break;
                        default:
                    }
                    break;
                //退出
                default:
                    flag = false;
                    break;
            }
        }
    }
}
